home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / timeit.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  12KB  |  357 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """Tool for measuring execution time of small code snippets.
  5.  
  6. This module avoids a number of common traps for measuring execution
  7. times.  See also Tim Peters' introduction to the Algorithms chapter in
  8. the Python Cookbook, published by O'Reilly.
  9.  
  10. Library usage: see the Timer class.
  11.  
  12. Command line usage:
  13.     python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]
  14.  
  15. Options:
  16.   -n/--number N: how many times to execute 'statement' (default: see below)
  17.   -r/--repeat N: how many times to repeat the timer (default 3)
  18.   -s/--setup S: statement to be executed once initially (default 'pass')
  19.   -t/--time: use time.time() (default on Unix)
  20.   -c/--clock: use time.clock() (default on Windows)
  21.   -v/--verbose: print raw timing results; repeat for more digits precision
  22.   -h/--help: print this usage message and exit
  23.   statement: statement to be timed (default 'pass')
  24.  
  25. A multi-line statement may be given by specifying each line as a
  26. separate argument; indented lines are possible by enclosing an
  27. argument in quotes and using leading spaces.  Multiple -s options are
  28. treated similarly.
  29.  
  30. If -n is not given, a suitable number of loops is calculated by trying
  31. successive powers of 10 until the total time is at least 0.2 seconds.
  32.  
  33. The difference in default timer function is because on Windows,
  34. clock() has microsecond granularity but time()'s granularity is 1/60th
  35. of a second; on Unix, clock() has 1/100th of a second granularity and
  36. time() is much more precise.  On either platform, the default timer
  37. functions measure wall clock time, not the CPU time.  This means that
  38. other processes running on the same computer may interfere with the
  39. timing.  The best thing to do when accurate timing is necessary is to
  40. repeat the timing a few times and use the best time.  The -r option is
  41. good for this; the default of 3 repetitions is probably enough in most
  42. cases.  On Unix, you can use clock() to measure CPU time.
  43.  
  44. Note: there is a certain baseline overhead associated with executing a
  45. pass statement.  The code here doesn't try to hide it, but you should
  46. be aware of it.  The baseline overhead can be measured by invoking the
  47. program without arguments.
  48.  
  49. The baseline overhead differs between Python versions!  Also, to
  50. fairly compare older Python versions to Python 2.3, you may want to
  51. use python -O for the older versions to avoid timing SET_LINENO
  52. instructions.
  53. """
  54. import gc
  55. import sys
  56. import time
  57.  
  58. try:
  59.     import itertools
  60. except ImportError:
  61.     itertools = None
  62.  
  63. __all__ = [
  64.     'Timer']
  65. dummy_src_name = '<timeit-src>'
  66. default_number = 1000000
  67. default_repeat = 3
  68. if sys.platform == 'win32':
  69.     default_timer = time.clock
  70. else:
  71.     default_timer = time.time
  72. template = '\ndef inner(_it, _timer):\n    %(setup)s\n    _t0 = _timer()\n    for _i in _it:\n        %(stmt)s\n    _t1 = _timer()\n    return _t1 - _t0\n'
  73.  
  74. def reindent(src, indent):
  75.     '''Helper to reindent a multi-line statement.'''
  76.     return src.replace('\n', '\n' + ' ' * indent)
  77.  
  78.  
  79. def _template_func(setup, func):
  80.     '''Create a timer function. Used if the "statement" is a callable.'''
  81.     
  82.     def inner(_it, _timer, _func = (func,)):
  83.         setup()
  84.         _t0 = _timer()
  85.         for _i in _it:
  86.             _func()
  87.         
  88.         _t1 = _timer()
  89.         return _t1 - _t0
  90.  
  91.     return inner
  92.  
  93.  
  94. class Timer:
  95.     """Class for timing execution speed of small code snippets.
  96.  
  97.     The constructor takes a statement to be timed, an additional
  98.     statement used for setup, and a timer function.  Both statements
  99.     default to 'pass'; the timer function is platform-dependent (see
  100.     module doc string).
  101.  
  102.     To measure the execution time of the first statement, use the
  103.     timeit() method.  The repeat() method is a convenience to call
  104.     timeit() multiple times and return a list of results.
  105.  
  106.     The statements may contain newlines, as long as they don't contain
  107.     multi-line string literals.
  108.     """
  109.     
  110.     def __init__(self, stmt = 'pass', setup = 'pass', timer = default_timer):
  111.         '''Constructor.  See class doc string.'''
  112.         self.timer = timer
  113.         ns = { }
  114.         if isinstance(stmt, basestring):
  115.             stmt = reindent(stmt, 8)
  116.             if isinstance(setup, basestring):
  117.                 setup = reindent(setup, 4)
  118.                 src = template % {
  119.                     'stmt': stmt,
  120.                     'setup': setup }
  121.             elif callable(setup):
  122.                 src = template % {
  123.                     'stmt': stmt,
  124.                     'setup': '_setup()' }
  125.                 ns['_setup'] = setup
  126.             else:
  127.                 raise ValueError('setup is neither a string nor callable')
  128.             self.src = isinstance(setup, basestring)
  129.             code = compile(src, dummy_src_name, 'exec')
  130.             exec code in globals(), ns
  131.             self.inner = ns['inner']
  132.         elif callable(stmt):
  133.             self.src = None
  134.             if isinstance(setup, basestring):
  135.                 _setup = setup
  136.                 
  137.                 def setup():
  138.                     exec _setup in globals(), ns
  139.  
  140.             elif not callable(setup):
  141.                 raise ValueError('setup is neither a string nor callable')
  142.             
  143.             self.inner = _template_func(setup, stmt)
  144.         else:
  145.             raise ValueError('stmt is neither a string nor callable')
  146.         return isinstance(stmt, basestring)
  147.  
  148.     
  149.     def print_exc(self, file = None):
  150.         '''Helper to print a traceback from the timed code.
  151.  
  152.         Typical use:
  153.  
  154.             t = Timer(...)       # outside the try/except
  155.             try:
  156.                 t.timeit(...)    # or t.repeat(...)
  157.             except:
  158.                 t.print_exc()
  159.  
  160.         The advantage over the standard traceback is that source lines
  161.         in the compiled template will be displayed.
  162.  
  163.         The optional file argument directs where the traceback is
  164.         sent; it defaults to sys.stderr.
  165.         '''
  166.         import linecache as linecache
  167.         import traceback as traceback
  168.         if self.src is not None:
  169.             linecache.cache[dummy_src_name] = (len(self.src), None, self.src.split('\n'), dummy_src_name)
  170.         
  171.         traceback.print_exc(file = file)
  172.  
  173.     
  174.     def timeit(self, number = default_number):
  175.         """Time 'number' executions of the main statement.
  176.  
  177.         To be precise, this executes the setup statement once, and
  178.         then returns the time it takes to execute the main statement
  179.         a number of times, as a float measured in seconds.  The
  180.         argument is the number of times through the loop, defaulting
  181.         to one million.  The main statement, the setup statement and
  182.         the timer function to be used are passed to the constructor.
  183.         """
  184.         if itertools:
  185.             it = itertools.repeat(None, number)
  186.         else:
  187.             it = [
  188.                 None] * number
  189.         gcold = gc.isenabled()
  190.         gc.disable()
  191.         timing = self.inner(it, self.timer)
  192.         if gcold:
  193.             gc.enable()
  194.         
  195.         return timing
  196.  
  197.     
  198.     def repeat(self, repeat = default_repeat, number = default_number):
  199.         """Call timeit() a few times.
  200.  
  201.         This is a convenience function that calls the timeit()
  202.         repeatedly, returning a list of results.  The first argument
  203.         specifies how many times to call timeit(), defaulting to 3;
  204.         the second argument specifies the timer argument, defaulting
  205.         to one million.
  206.  
  207.         Note: it's tempting to calculate mean and standard deviation
  208.         from the result vector and report these.  However, this is not
  209.         very useful.  In a typical case, the lowest value gives a
  210.         lower bound for how fast your machine can run the given code
  211.         snippet; higher values in the result vector are typically not
  212.         caused by variability in Python's speed, but by other
  213.         processes interfering with your timing accuracy.  So the min()
  214.         of the result is probably the only number you should be
  215.         interested in.  After that, you should look at the entire
  216.         vector and apply common sense rather than statistics.
  217.         """
  218.         r = []
  219.         for i in range(repeat):
  220.             t = self.timeit(number)
  221.             r.append(t)
  222.         
  223.         return r
  224.  
  225.  
  226.  
  227. def timeit(stmt = 'pass', setup = 'pass', timer = default_timer, number = default_number):
  228.     '''Convenience function to create Timer object and call timeit method.'''
  229.     return Timer(stmt, setup, timer).timeit(number)
  230.  
  231.  
  232. def repeat(stmt = 'pass', setup = 'pass', timer = default_timer, repeat = default_repeat, number = default_number):
  233.     '''Convenience function to create Timer object and call repeat method.'''
  234.     return Timer(stmt, setup, timer).repeat(repeat, number)
  235.  
  236.  
  237. def main(args = None):
  238.     '''Main program, used when run as a script.
  239.  
  240.     The optional argument specifies the command line to be parsed,
  241.     defaulting to sys.argv[1:].
  242.  
  243.     The return value is an exit code to be passed to sys.exit(); it
  244.     may be None to indicate success.
  245.  
  246.     When an exception happens during timing, a traceback is printed to
  247.     stderr and the return value is 1.  Exceptions at other times
  248.     (including the template compilation) are not caught.
  249.     '''
  250.     if args is None:
  251.         args = sys.argv[1:]
  252.     
  253.     import getopt as getopt
  254.     
  255.     try:
  256.         (opts, args) = getopt.getopt(args, 'n:s:r:tcvh', [
  257.             'number=',
  258.             'setup=',
  259.             'repeat=',
  260.             'time',
  261.             'clock',
  262.             'verbose',
  263.             'help'])
  264.     except getopt.error:
  265.         err = None
  266.         print err
  267.         print 'use -h/--help for command line help'
  268.         return 2
  269.  
  270.     timer = default_timer
  271.     if not '\n'.join(args):
  272.         pass
  273.     stmt = 'pass'
  274.     number = 0
  275.     setup = []
  276.     repeat = default_repeat
  277.     verbose = 0
  278.     precision = 3
  279.     for o, a in opts:
  280.         if o in ('-n', '--number'):
  281.             number = int(a)
  282.         
  283.         if o in ('-s', '--setup'):
  284.             setup.append(a)
  285.         
  286.         if o in ('-r', '--repeat'):
  287.             repeat = int(a)
  288.             if repeat <= 0:
  289.                 repeat = 1
  290.             
  291.         
  292.         if o in ('-t', '--time'):
  293.             timer = time.time
  294.         
  295.         if o in ('-c', '--clock'):
  296.             timer = time.clock
  297.         
  298.         if o in ('-v', '--verbose'):
  299.             if verbose:
  300.                 precision += 1
  301.             
  302.             verbose += 1
  303.         
  304.         if o in ('-h', '--help'):
  305.             print __doc__,
  306.             return 0
  307.     
  308.     if not '\n'.join(setup):
  309.         pass
  310.     setup = 'pass'
  311.     import os as os
  312.     sys.path.insert(0, os.curdir)
  313.     t = Timer(stmt, setup, timer)
  314.     if number == 0:
  315.         for i in range(1, 10):
  316.             number = 10 ** i
  317.             
  318.             try:
  319.                 x = t.timeit(number)
  320.             except:
  321.                 o in ('-h', '--help')
  322.                 t.print_exc()
  323.                 return 1
  324.  
  325.             if x >= 0.2:
  326.                 break
  327.                 continue
  328.             None if verbose else o in ('-h', '--help')
  329.         
  330.     
  331.     
  332.     try:
  333.         r = t.repeat(repeat, number)
  334.     except:
  335.         t.print_exc()
  336.         return 1
  337.  
  338.     best = min(r)
  339.     if verbose:
  340.         print 'raw times:', []([ '%.*g' % (precision, x) for x in r ])
  341.     
  342.     print '%d loops,' % number,
  343.     usec = best * 1e+06 / number
  344.     if usec < 1000:
  345.         print 'best of %d: %.*g usec per loop' % (repeat, precision, usec)
  346.     else:
  347.         msec = usec / 1000
  348.         if msec < 1000:
  349.             print 'best of %d: %.*g msec per loop' % (repeat, precision, msec)
  350.         else:
  351.             sec = msec / 1000
  352.             print 'best of %d: %.*g sec per loop' % (repeat, precision, sec)
  353.  
  354. if __name__ == '__main__':
  355.     sys.exit(main())
  356.  
  357.